# Create your views here.
from onm.onk.models import Page
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django import newforms as forms
from django.views.generic import list_detail
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.models import User
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.http import Http404

class SearchForm(forms.Form):
    text = forms.CharField(label="Enter search term")
    search_content = forms.BooleanField(label="Search content", required=False)
    
def search_page(request):
    if request.method == "POST":
        f = SearchForm(request.POST)
        if not f.is_valid():
            return render_to_response("onk/search.html", {"form":f})
        else:
            pages = Page.objects.filter(name__contains = f.cleaned_data["text"])
            contents = []
            if f.cleaned_data["search_content"]:    
                contents = Page.objects.filter(content__contains = f.cleaned_data["text"])
            return render_to_response("onk/search.html", {"form":f, "pages":pages, "contents":contents})
            
    f = SearchForm()
    return render_to_response("onk/search.html", {"form":f})
    
specialPages = {"SearchPage": search_page}

def view_page(request, page_name):
    if page_name in specialPages:
        return specialPages[page_name](request)
    try:
        page = Page.objects.get(pk=page_name)
    except Page.DoesNotExist:
        return render_to_response("onk/create.html", {"page_name":page_name})
    content = page.content
    return list_detail.object_detail(
        request,
        queryset = Page.objects.all(),
        object_id = page_name,
    )

@login_required
def edit_page(request, page_name): 
    try:
        page = Page.objects.get(pk=page_name)
        if not request.user.is_staff and not page.is_author(request.user):
            raise Http404
        PageForm = forms.models.form_for_instance(page)        
    except:
        PageForm = forms.models.form_for_model(Page)
    PageForm.base_fields['raw_content'].widget=forms.Textarea(attrs={'rows': 20, 'cols': 60})
    if request.method == 'POST':
        form = PageForm(request.POST)
        if form.is_valid():
            
            page_form = form.save(commit=False)
            page_form.name = page_name
            # Only edit author on creation
            #try:
            print PageForm.base_field['author'].initial
            #except:
            page_form.author = request.user
            page_form.save()
            return HttpResponseRedirect( page_form.get_absolute_url() )
    else:
        form = PageForm()
        return render_to_response("onk/edit.html",
                                {"form":form, "page_name":page_name},
                                context_instance=RequestContext(request))